import axios from 'axios'
import { getCookie } from '@/utils'
import { Toast } from 'antd-mobile'

let loadingReqCount = 0 // 统计loading个数
let loadingInstance: any = null // 正在loading的实例

function showLoading () {
  if (loadingReqCount === 0) {
    Toast.show({
      icon: 'loading',
      content: '加载中...',
      maskClickable: false, // 不可点击关闭
      duration: 0 // 无限随间
    })
  }
  loadingReqCount++
}

function closeLoading () {
  loadingReqCount--
  loadingReqCount = Math.max(loadingReqCount, 0) // 保证大于等于0
  if (loadingReqCount === 0 || loadingInstance) {
    hideLoading()
  }
}

const hideLoading = () => {
  // loadingReqCount 需要二次判断，因为后续接口调用会增加这个值，就不能直接关闭
  if (loadingReqCount === 0) {
    Toast.clear()
    loadingInstance = null
  }
}

export function request (config: any) {
  const instance = axios.create({
    baseURL: 'https://api.shop.eduwork.cn/',
    timeout: 5000
  })

  // 请求拦截
  instance.interceptors.request.use(config => {
    showLoading()
    const token = getCookie('token')
    if(token) {
      config.headers.Authorization = 'Bearer' + token
    }
    return config
  }, err => {
    closeLoading()
    console.log(err)
  })
  
  // 响应拦截
  instance.interceptors.response.use(res => {
    closeLoading()
    return res
  }, err => { // 请求超时或者断网
    closeLoading()
    if(err.code === 'ECONNABORTED' || err.code === "ERR_NETWORK") {
      if (window.location.pathname === '/login' || window.location.pathname === '/register') { // 登陆和注册页面请求超时 直接谈信息框
        Toast.show({ content: '网络超时,请重试', icon: 'fail', duration: 1500 })
      } else { // 其他页面请求超时, 需要拿到错误信息, 根据错误信息将loading隐藏, 然后显示超时信息内容
        return Promise.reject(err)
      }
    } else { // 没有请求超时
      if(err.status === 401 && (window.location.pathname === '/login' || window.location.pathname === '/register')) {
        Toast.show({content: '邮箱或密码有误', icon: 'fail', duration: 1500})
      } else if(err.status === 401) {
        Toast.show({ content: '请先登录呀', icon: 'fail', duration: 1500, afterClose: () => { window.location.href = '/login' }})
      } else {
        Toast.show({ icon: 'fail', content: err.response.data.errors[Object.keys(err.response.data.errors)[0]][0], duration: 1500 })
      }
    }
  })
  return instance(config)
}